package com.neusoft.nep.NEPM.controller;

import com.neusoft.nep.entity.nepgResult;
import com.neusoft.nep.entity.nepsFeedback;
import com.neusoft.tools.AddressMapUtils;
import com.neusoft.tools.AlertUtils;
import com.neusoft.tools.FXMLUtils;
import com.neusoft.tools.FileUtils;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class confirmDataViewController {
    @FXML
    ComboBox<String> provinces, cities;
    private ObservableList tableList = FXCollections.observableArrayList();
    @FXML
    private List<nepgResult> fbs = new ArrayList<>();
    @FXML
    private nepsFeedback nepsf;
    @FXML
    private TableView tableView;
    @FXML
    private Button btn_out, back;
    @FXML
    private TreeView treeview;
    @FXML
    private TreeItem To_AqiTrendTotalStatisView;
    @FXML
    private TreeItem To_AqiSeperatedStatisView;
    @FXML
    private TreeItem To_OtherStatisView;
    @FXML
    private TreeItem To_ProvinceDataTotalStatisView;
    @FXML
    private TreeItem To_confirmDataView;
    @FXML
    private TreeItem To_publicAqiDataList;
    @FXML
    private TableColumn<nepgResult, String> coldata, colusername, colphoneNumber, colprovince, colcity, collevel;

    @FXML
    public void initialize() throws IOException {

        fbs = FileUtils.readListObject("NEPGresult.txt");

        tableView.setItems(tableList);

        colphoneNumber.setCellValueFactory(new PropertyValueFactory<>("phone"));
        colusername.setCellValueFactory(new PropertyValueFactory<>("username"));
        coldata.setCellValueFactory(new PropertyValueFactory<>("data"));
        colcity.setCellValueFactory(new PropertyValueFactory<>("city"));
        colprovince.setCellValueFactory(new PropertyValueFactory<>("province"));
        collevel.setCellValueFactory(new PropertyValueFactory<>("realLevel"));

        tableList.setAll(fbs);

        setupComboBoxListeners();
        tableView.setEditable(true);
        colusername.setCellFactory(javafx.scene.control.cell.TextFieldTableCell.forTableColumn());
        setupTreeViewListeners(); // 将 TreeView 逻辑封装，保持代码整洁
        treeview.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == To_AqiSeperatedStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out,"NEPM/view/AqiSeperatedStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            } else if (newValue == To_AqiTrendTotalStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out,"NEPM/view/AqiTrendTotalStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            } else if (newValue == To_OtherStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out,"NEPM/view/OtherStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            } else if (newValue == To_ProvinceDataTotalStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out,"NEPM/view/ProvinceDataTotalStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }

            }

            else if (newValue == To_confirmDataView) {
                try {
                    FXMLUtils.switchToShow(btn_out, "NEPM/view/confirmDataView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            }else if (newValue == To_publicAqiDataList) {
                try {
                    FXMLUtils.switchToShow(btn_out, "NEPM/view/publicAqiDataList.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            }
        });
    }

    /**
     * 封装 TreeView 的监听器设置 (内容为您原来的代码)
     */
    private void setupTreeViewListeners() {
        treeview.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == To_AqiSeperatedStatisView) {
                try {
                    FXMLUtils.switchToShow(btn_out, "NEPM/view/AqiSeperatedStatisView.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            } else if (newValue == To_AqiTrendTotalStatisView) {
                // ... 您所有的 else if 跳转逻辑都放在这里，保持不变 ...
            } else if (newValue == To_publicAqiDataList) {
                try {
                    FXMLUtils.switchToShow(btn_out, "NEPM/view/publicAqiDataList.fxml");
                } catch (IOException e) {
                    e.printStackTrace();
                    AlertUtils.showDialog("错误", "页面跳转失败: " + e.getMessage());
                }
            }
        });
    }
    /**
     * 设置省份和城市 ComboBox 的监听器，以实现联动和查询
     * @throws IOException 如果地址文件读取失败
     */
    private void setupComboBoxListeners() throws IOException {
        Map<String, List<String>> addressMap = AddressMapUtils.initAddressMap();

        provinces.setItems(FXCollections.observableArrayList(addressMap.keySet()));

        // 添加对【省份 ComboBox】的监听
        provinces.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
            if (newValue != null) {

                cities.getSelectionModel().clearSelection();
                cities.getItems().clear();

                List<String> cityList = addressMap.get(newValue);
                if (cityList != null) {
                    cities.setItems(FXCollections.observableArrayList(cityList));
                }

                queryData();
            }
        });

        // 添加对【城市 ComboBox】的监听
        cities.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
            // 只有当城市被有效选择后，才再次执行查询
            if (newValue != null) {
                queryData();
            }
        });
    }
    public void Log_out() throws IOException {
        FXMLUtils.switchToShow(btn_out, "NEPM/view/LogInView.fxml");
    }

    public nepsFeedback set(nepsFeedback n) {
        nepsf = n;
        return nepsf;
    }

    public void back() throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../view/publicAqiDataList.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = new Scene(root);
        Stage stage = (Stage) back.getScene().getWindow();
        stage.setScene(scene);
        stage.show();
    }
    public void queryData() {
        String selectedProvince = provinces.getSelectionModel().getSelectedItem();
        String selectedCity = cities.getSelectionModel().getSelectedItem();


        List<nepgResult> filteredData = fbs.stream()
                .filter(result -> {

                    boolean provinceMatch = (selectedProvince == null) || selectedProvince.equals(result.getProvince());
                    boolean cityMatch = (selectedCity == null) || selectedCity.equals(result.getCity());
                    // 最终结果要求两者都匹配
                    return provinceMatch && cityMatch;
                })
                .collect(Collectors.toList());

        // 使用 setAll 一次性高效更新 TableView 的内容
        tableList.setAll(filteredData);
    }
    public void delfeedback() throws IOException {
        nepgResult selectedFeedback = (nepgResult) tableView.getSelectionModel().getSelectedItem();
        tableList.remove(selectedFeedback);
        fbs.remove(selectedFeedback);
        AlertUtils.showDialog("删除信息","删除成功");
        System.out.println("out");
    }
}